package com.creditcmsplt.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.creditcmsplt.common.CommonPhpService;
import com.creditcmsplt.entity.PhpResult;
import com.creditcmsplt.entity.Token;
import com.creditcmsplt.entity.param.SncfAuthorityReq;
import com.creditcmsplt.entity.param.SncfAuthorityReqSystem;
import com.creditcmsplt.entity.param.SncfAuthorityRsp;
import com.creditcmsplt.entity.param.SncfAuthorityRspData;
import com.creditcmsplt.entity.param.SncfDownloadReq;
import com.creditcmsplt.entity.param.SncfDownloadReqData;
import com.creditcmsplt.entity.param.SncfDownloadReqSystem;
import com.creditcmsplt.entity.param.SncfDownloadRsp;
import com.creditcmsplt.entity.param.SncfDownloadRspData;
import com.creditcmsplt.entity.param.SncfSendMsgReq;
import com.creditcmsplt.entity.param.SncfSendMsgReqSystem;
import com.creditcmsplt.entity.param.SncfSendMsgRsp;
import com.creditcmsplt.entity.param.SncfSendMsgRspData;
import com.creditcmsplt.entity.param.SncfStatusReq;
import com.creditcmsplt.entity.param.SncfStatusReqData;
import com.creditcmsplt.entity.param.SncfStatusReqSystem;
import com.creditcmsplt.entity.param.SncfStatusRsp;
import com.creditcmsplt.entity.param.SncfStatusRspData;
import com.creditcmsplt.entity.param.SncfUpIdentifyReq;
import com.creditcmsplt.entity.param.SncfUpIdentifyReqData;
import com.creditcmsplt.entity.param.SncfUpIdentifyReqSystem;
import com.creditcmsplt.entity.param.SncfUpIdentifyRsp;
import com.creditcmsplt.entity.param.SncfUpIdentifyRspData;
import com.creditcmsplt.entity.param.SncfUpSignReq;
import com.creditcmsplt.entity.param.SncfUpSignReqData;
import com.creditcmsplt.entity.param.SncfUpSignReqSystem;
import com.creditcmsplt.entity.param.SncfUpSignRsp;
import com.creditcmsplt.entity.param.SncfUpSignRspData;
import com.creditcmsplt.entity.param.SncfUpUserInfoReq;
import com.creditcmsplt.entity.param.SncfUpUserInfoReqData;
import com.creditcmsplt.entity.param.SncfUpUserInfoReqSystem;
import com.creditcmsplt.entity.param.SncfUpUserInfoRsp;
import com.creditcmsplt.entity.param.SncfUpUserInfoRspData;
import com.creditcmsplt.service.CreditApiService;
import com.creditcmsplt.service.CreditAuothService;
import com.creditcmsplt.service.CreditSysLogService;
import com.creditcmsplt.util.Base64Util;
import com.creditcmsplt.util.TextUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 征信资料上传（现场）
 * 
 * @author leiyangjun
 *
 */
@RestController
@RequestMapping("snCollectInfo")
@Api(value = "snCollectInfo", tags = { "5.0,现场版资料收集" },description="snCollectInfo")
public class SnCollectInfoController {

	private final Logger log = LoggerFactory.getLogger(SnCollectInfoController.class);

	@Autowired
	private CreditAuothService creditAuothService;

	@Autowired
	private CommonPhpService phpService;
	
	@Autowired
	private CreditApiService creditApiService;
	
	@Autowired
	private CreditSysLogService creditSysLogService;

	@ApiOperation(value="上传身份证正反面",notes="资料收集第一步,上传身份证正反面")
	@RequestMapping(value = "/upIdentify", method = RequestMethod.POST)
	public SncfUpIdentifyRsp upIdentify(@RequestBody SncfUpIdentifyReq params,HttpServletRequest req) {
		SncfUpIdentifyRsp collectInfoUpRspInfo=new SncfUpIdentifyRsp();
		SncfUpIdentifyReqSystem systemInfo=params.getSystem();
		SncfUpIdentifyReqData dataParam=params.getData();
		
		int code=1;
		String msg="成功";
		if(code==1&&(systemInfo==null||TextUtils.isEmpty(systemInfo.getToken()))) {
			code=-1;
			msg="没有授权信息";
		}
		if(code==1&&dataParam==null) {
			code=-1;
			msg="没有必须参数";
		}
		if(code==1&&(dataParam==null||TextUtils.isEmpty(dataParam.getIdentify()))) {
			code=-1;
			msg="没有身份证正面照";
		}
		if(code==1&&(dataParam==null||TextUtils.isEmpty(dataParam.getIdentify_back()))) {
			code=-1;
			msg="没有身份证反面照";
		}
		if(code==1&&(dataParam==null||TextUtils.isEmpty(dataParam.getIdentifyno()))) {
			code=-1;
			msg="没有身份证号码";
		}
		if(code==1&&(dataParam==null||TextUtils.isEmpty(dataParam.getAvatar()))) {
			code=-1;
			msg="没有身份证图像照";
		}
		if(code==1&&(dataParam.getIsMachine()==null||!(dataParam.getIsMachine().equals(0)||dataParam.getIsMachine().equals(1)))) {
			code=-1;
			msg="照片来源是否高拍仪必填且只能是0或1";
		}
		if(code==1&&(dataParam==null||TextUtils.isEmpty(dataParam.getHandHoldIdentify()))) {
			code=-1;
			msg="没有手持证件照";
		}
//		if(code==1&&(dataParam==null||TextUtils.isEmpty(dataParam.getAuthority()))) {
//			code=-1;
//			msg="没有授权书照片";
//		}
		if(code==1&&!Base64Util.checkImage(dataParam.getIdentify(), "jpeg")) {
			code=-1;
			msg="身份证正面照只支持jpeg/jpg格式";
		}
		if(code==1&&!Base64Util.checkImage(dataParam.getIdentify_back(), "jpeg")) {
			code=-1;
			msg="身份证反面照只支持jpeg/jpg格式";
		}
		if(code==1&&!Base64Util.checkImage(dataParam.getAvatar(), "jpeg")) {
			code=-1;
			msg="图像照只支持jpeg/jpg格式";
		}
		if(code==1&&!Base64Util.checkImage(dataParam.getHandHoldIdentify(), "jpeg")) {
			code=-1;
			msg="手持证件照只支持jpeg/jpg格式";
		}
		
		double maxSize=2.0;
		if(code==1&&(
				!Base64Util.checkSize(dataParam.getIdentify(), maxSize)||
				!Base64Util.checkSize(dataParam.getIdentify_back(), maxSize)||
				!Base64Util.checkSize(dataParam.getAvatar(), maxSize)||
				!Base64Util.checkSize(dataParam.getHandHoldIdentify(), maxSize)
				)) {
			code=-1;
			msg="有照片超过2M上限，所有照片最大支持2M上传";
		}
		
		Map<String, Object> creditAuoth =code==1?this.creditAuothService.checkToken(systemInfo.getToken()):new HashMap<String, Object>();
		if(code==1&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}//credit_id
		Token token=code==1?creditSysLogService.getToken((Long)creditAuoth.get("credit_id")):null;
		if(code==1&&token==null) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		PhpResult phpResult=code==1?phpService.snUpIdentify(params, token.getApitoken()):null;
		String cid="";
		if(code==1&&phpResult!=null) {
			code=phpResult.getError().equals(0)?1:-1;
			msg=phpResult.getReason();
			cid=phpResult.getCid()==null?"":phpResult.getCid();
		}else if(code==1&&phpResult==null){
			code=-1;
			msg="调用失败，服务无响应";
		}
		
		creditApiService.insert(systemInfo.getToken(), "", "", code, req.getServletPath());//统计接口调用次数
		
		SncfUpIdentifyRspData data=new SncfUpIdentifyRspData();
		data.setCode(code);
		data.setMsg(msg);
		data.setCid(cid);
		collectInfoUpRspInfo.setData(data);
		return collectInfoUpRspInfo;
	}
	
	@ApiOperation(value="上传被征信人身份信息",notes="资料收集第二步,上传用户信息")
	@RequestMapping(value = "/upUserInfo", method = RequestMethod.POST)
	public SncfUpUserInfoRsp upUserInfo(@RequestBody SncfUpUserInfoReq params,HttpServletRequest req) {
		SncfUpUserInfoRsp collectInfoUpRspInfo=new SncfUpUserInfoRsp();
		SncfUpUserInfoReqSystem systemInfo=params.getSystem();
		SncfUpUserInfoReqData dataParam=params.getData();
		
		int code=1;
		String msg="成功";
		if(code==1&&(systemInfo==null||TextUtils.isEmpty(systemInfo.getToken()))) {
			code=-1;
			msg="没有授权信息";
		}
		if(code==1&&(dataParam==null||TextUtils.isEmpty(dataParam.getCid()))) {
			code=-1;
			msg="没有上传识别码";
		}
		if(code==1&&(dataParam==null||
				TextUtils.isEmpty(dataParam.getUserName())||
				TextUtils.isEmpty(dataParam.getGender())||
				TextUtils.isEmpty(dataParam.getNational())||
				TextUtils.isEmpty(dataParam.getBirthday())||
				TextUtils.isEmpty(dataParam.getIdentifyno())||
				TextUtils.isEmpty(dataParam.getCertificateExpire())||
				TextUtils.isEmpty(dataParam.getIssuingAuthority())||
				TextUtils.isEmpty(dataParam.getAddress())||
				TextUtils.isEmpty(dataParam.getPhoneNumber()))) {
			code=-1;
			msg="身份证信息不完整";
		}
		if(code==1&&!checkCertificateExpire(dataParam.getCertificateExpire())) {
			code=-1;
			msg="证件有效期格式不正确或身份证已经过期";
		}
		if(code==1&&!(dataParam.getGender().equals("男")||dataParam.getGender().equals("女"))) {
			code=-1;
			msg="性别只能是男或女";
		}
		Map<String, Object> creditAuoth =code==1?this.creditAuothService.checkToken(systemInfo.getToken()):new HashMap<String, Object>();
		if(code==1&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}//credit_id
		Token token=code==1?creditSysLogService.getToken((Long)creditAuoth.get("credit_id")):null;
		if(code==1&&token==null) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		PhpResult phpResult=code==1?phpService.snUpUserInfo(params, token.getApitoken()):null;
		if(code==1&&phpResult!=null) {
			code=phpResult.getError().equals(0)?1:-1;
			msg=phpResult.getReason();
		}else if(code==1&&phpResult==null){
			code=-1;
			msg="调用失败，服务无响应";
		}
		
		creditApiService.insert(systemInfo.getToken(), "", "", code, req.getServletPath());//统计接口调用次数
		
		SncfUpUserInfoRspData data=new SncfUpUserInfoRspData();
		data.setCode(code);
		data.setMsg(msg);
		collectInfoUpRspInfo.setData(data);
		return collectInfoUpRspInfo;
	}
	
	private boolean checkCertificateExpire(String certificateExpire) {
		boolean resultFlag=true;
		int idf=certificateExpire.indexOf("-");
		resultFlag=idf<=0?false:true;
		String dataStart=resultFlag?certificateExpire.substring(0, certificateExpire.indexOf("-")):"";
		String dataEnd=resultFlag?certificateExpire.substring(certificateExpire.indexOf("-")+1, certificateExpire.length()):"";
		if(TextUtils.isEmpty(dataStart)||TextUtils.isEmpty(dataEnd)) {
			resultFlag=false;
		}
		Date dateStart=null;
		if(resultFlag) {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
			try {
				dateStart=sdf.parse(dataStart);
			} catch (ParseException e) {
				//e.printStackTrace();
				resultFlag=false;
			}
		}
		Date dateEnd=null;
		if(resultFlag&&!dataEnd.equals("长期")) {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
			try {
				dateEnd=sdf.parse(dataEnd);
			} catch (ParseException e) {
				//e.printStackTrace();
				resultFlag=false;
			}
		}
		if(resultFlag&&dateStart!=null) {
			resultFlag=dateStart.compareTo(new Date())>0?false:true;//开始时间比当前日期大
		}
		if(resultFlag&&!TextUtils.isEmpty(dataEnd)&&!dataEnd.equals("长期")) {
			resultFlag=dateEnd!=null&&dateEnd.compareTo(new Date())<0?false:true;//结束时间比当前日期小
		}
		if(resultFlag&&dateEnd!=null&&dateStart!=null) {
			resultFlag=dateEnd.compareTo(dateStart)<=0?false:true;
		}
		return resultFlag;
	} 
	
	@ApiOperation(value="上传签名照",notes="资料收集第三步,上传签名照")
	@RequestMapping(value = "/upSign", method = RequestMethod.POST)
	public SncfUpSignRsp upSign(@RequestBody SncfUpSignReq params,HttpServletRequest req) {
		SncfUpSignRsp collectInfoUpRspInfo=new SncfUpSignRsp();
		SncfUpSignReqSystem systemInfo=params.getSystem();
		SncfUpSignReqData dataParam=params.getData();
		
		int code=1;
		String msg="成功";
		if(code==1&&(systemInfo==null||TextUtils.isEmpty(systemInfo.getToken()))) {
			code=-1;
			msg="没有授权信息";
		}
		if(code==1&&(dataParam==null||TextUtils.isEmpty(dataParam.getCid()))) {
			code=-1;
			msg="没有上传识别码";
		}
		if(code==1&&(dataParam==null||
				TextUtils.isEmpty(dataParam.getSign()))) {
			code=-1;
			msg="没有签名照";
		}
		if(code==1&&!Base64Util.checkImage(dataParam.getSign(), "png")) {
			code=-1;
			msg="签名照只支持png格式";
		}
		if(code==1&&!Base64Util.checkSize(dataParam.getSign(), 2.0)) {
			code=-1;
			msg="签名照最大限制2M";
		}
		if(code==1&&(dataParam==null||
				TextUtils.isEmpty(dataParam.getIdentifyno()))) {
			code=-1;
			msg="没有身份证号码";
		}
		Map<String, Object> creditAuoth =code==1?this.creditAuothService.checkToken(systemInfo.getToken()):new HashMap<String, Object>();
		if(code==1&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}//credit_id
		Token token=code==1?creditSysLogService.getToken((Long)creditAuoth.get("credit_id")):null;
		if(code==1&&token==null) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		PhpResult phpResult=code==1?phpService.snUpSign(params, token.getApitoken()):null;
		if(code==1&&phpResult!=null) {
			code=phpResult.getError().equals(0)?1:-1;
			msg=phpResult.getReason();
		}else if(code==1&&phpResult==null){
			code=-1;
			msg="调用失败，服务无响应";
		}
		
		creditApiService.insert(systemInfo.getToken(), "", "", code, req.getServletPath());//统计接口调用次数
		
		SncfUpSignRspData data=new SncfUpSignRspData();
		data.setCode(code);
		data.setMsg(msg);
		collectInfoUpRspInfo.setData(data);
		return collectInfoUpRspInfo;
	}
	
	@ApiOperation(value="状态查询",notes="资料上传收集完后,通过该接口获取报告生成状态")
	@RequestMapping(value = "/queryStatus", method = RequestMethod.POST)
	public SncfStatusRsp queryStatus(@RequestBody SncfStatusReq params,HttpServletRequest req) {
		SncfStatusRsp collectInfoUpRspInfo=new SncfStatusRsp();
		SncfStatusReqSystem systemInfo=params.getSystem();
		SncfStatusReqData dataParam=params.getData();
		
		int code=1;
		String msg="成功";
		if(code==1&&(systemInfo==null||TextUtils.isEmpty(systemInfo.getToken()))) {
			code=-1;
			msg="没有授权信息";
		}
		if(code==1&&(dataParam==null||
				TextUtils.isEmpty(dataParam.getIdentifyno()))) {
			code=-1;
			msg="没有身份证号码";
		}
		Map<String, Object> creditAuoth =code==1?this.creditAuothService.checkToken(systemInfo.getToken()):new HashMap<String, Object>();
		if(code==1&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		Token token=code==1?creditSysLogService.getToken((Long)creditAuoth.get("credit_id")):null;
		if(code==1&&token==null) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		PhpResult phpResult=code==1?phpService.snQueryStatus(params, token.getApitoken(), creditAuoth.get("credit_id").toString()):null;
		String content="";
		if(code==1&&phpResult!=null) {
			code=phpResult.getError().equals(0)?phpResult.getStatus():-1;
			msg=TextUtils.isEmpty(phpResult.getProgress())?phpResult.getReason():phpResult.getProgress();
			content=phpResult.getContent();
		}else if(code==1&&phpResult==null){
			code=-1;
			msg="调用失败，服务无响应";
		}
		if(!TextUtils.isEmpty(content)) {
			msg+=" 退回或失败原因:"+content;
		}
		creditApiService.insert(systemInfo.getToken(), "", "", code, req.getServletPath());//统计接口调用次数
		
		SncfStatusRspData data=new SncfStatusRspData();
		data.setCode(code);
		data.setMsg(msg);
		collectInfoUpRspInfo.setData(data);
		return collectInfoUpRspInfo;
	}
	
	@ApiOperation(value="征信报告下载",notes="征信报告下载--下载的为excel文件,封装为base64字符,请自行转换")
	@RequestMapping(value = "/download", method = RequestMethod.POST)
	public SncfDownloadRsp download(@RequestBody SncfDownloadReq params,HttpServletRequest req) {
		SncfDownloadRsp collectInfoUpRspInfo=new SncfDownloadRsp();
		SncfDownloadReqSystem systemInfo=params.getSystem();
		SncfDownloadReqData dataParam=params.getData();
		
		int code=1;
		String msg="成功";
		if(code==1&&(systemInfo==null||TextUtils.isEmpty(systemInfo.getToken()))) {
			code=-1;
			msg="没有授权信息";
		}
		if(code==1&&(dataParam==null||
				TextUtils.isEmpty(dataParam.getIdentifyno()))) {
			code=-1;
			msg="没有身份证号码";
		}
		Map<String, Object> creditAuoth =code==1?this.creditAuothService.checkToken(systemInfo.getToken()):new HashMap<String, Object>();
		if(code==1&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		
		Token token=code==1?creditSysLogService.getToken((Long)creditAuoth.get("credit_id")):null;
		if(code==1&&token==null) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		PhpResult phpResult=code==1?phpService.snDownload(params, token.getApitoken(), creditAuoth.get("credit_id").toString()):null;
		String file="";
		if(code==1&&phpResult!=null) {
			code=phpResult.getError().equals(0)?1:-1;
			msg=TextUtils.isEmpty(phpResult.getReason())?"成功":phpResult.getReason();
			file=phpResult.getFile();
		}else if(code==1&&phpResult==null){
			code=-1;
			msg="调用失败，服务无响应";
		}
		
		creditApiService.insert(systemInfo.getToken(), "", "", code, req.getServletPath());//统计接口调用次数
		
		SncfDownloadRspData data=new SncfDownloadRspData();
		data.setCode(code);
		data.setMsg(msg);
		data.setContentBase64(file);
		collectInfoUpRspInfo.setData(data);
		return collectInfoUpRspInfo;
	}
	
	@ApiIgnore
	@RequestMapping(value = "/getAuthority", method = RequestMethod.POST)
	public SncfAuthorityRsp getAuthority(@RequestBody SncfAuthorityReq params,HttpServletRequest req) {
		SncfAuthorityRsp collectInfoUpRspInfo=new SncfAuthorityRsp();
		SncfAuthorityReqSystem systemInfo=params.getSystem();
		
		int code=1;
		String msg="成功";
		if(code==1&&(systemInfo==null||TextUtils.isEmpty(systemInfo.getToken()))) {
			code=-1;
			msg="没有授权信息";
		}
		Map<String, Object> creditAuoth =code==1?this.creditAuothService.checkToken(systemInfo.getToken()):new HashMap<String, Object>();
		if(code==1&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		
		Token token=code==1?creditSysLogService.getToken((Long)creditAuoth.get("credit_id")):null;
		if(code==1&&token==null) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		PhpResult phpResult=code==1?phpService.snAuthDown(token.getApitoken()):null;
		String file="";
		if(code==1&&phpResult!=null) {
			code=phpResult.getError().equals(0)?1:-1;
			msg=phpResult.getReason();
			file=phpResult.getFile();
		}else if(code==1&&phpResult==null){
			code=-1;
			msg="调用失败，服务无响应";
		}
		
		creditApiService.insert(systemInfo.getToken(), "", "", code, req.getServletPath());//统计接口调用次数
		
		SncfAuthorityRspData data=new SncfAuthorityRspData();
		data.setCode(code);
		data.setMsg(msg);
		data.setContentBase64(file);
		collectInfoUpRspInfo.setData(data);
		return collectInfoUpRspInfo;
	}
	
	@ApiOperation(value="发送短信",notes="发送下载征信报告的短信给贷款人")
	@RequestMapping(value = "/sendMsg", method = RequestMethod.POST)
	public SncfSendMsgRsp sendMsg(@RequestBody SncfSendMsgReq params,HttpServletRequest req) {
		SncfSendMsgRsp collectInfoUpRspInfo=new SncfSendMsgRsp();
		SncfSendMsgReqSystem systemInfo=params.getSystem();
		
		int code=1;
		String msg="成功";
		if(code==1&&(systemInfo==null||TextUtils.isEmpty(systemInfo.getToken()))) {
			code=-1;
			msg="没有授权信息";
		}
		Map<String, Object> creditAuoth =code==1?this.creditAuothService.checkToken(systemInfo.getToken()):new HashMap<String, Object>();
		if(code==1&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		
		Token token=code==1?creditSysLogService.getToken((Long)creditAuoth.get("credit_id")):null;
		if(code==1&&token==null) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		PhpResult phpResult=code==1?phpService.snSendMsg(token.getApitoken(), params.getData().getIdentifyno()):null;
		if(code==1&&phpResult!=null) {
			code=phpResult.getError().equals(0)?1:-1;
			msg=phpResult.getReason();
		}else if(code==1&&phpResult==null){
			code=-1;
			msg="调用失败，服务无响应";
		}
		
		creditApiService.insert(systemInfo.getToken(), "", "", code, req.getServletPath());//统计接口调用次数
		
		SncfSendMsgRspData data=new SncfSendMsgRspData();
		data.setCode(code);
		data.setMsg(msg);
		collectInfoUpRspInfo.setData(data);
		return collectInfoUpRspInfo;
	}
}
